const httpResult = require("../lib/httpResult");
const _ = require("lodash");
let router = require('koa-router')();
const MyEmitter = require('../lib/MyEmitter');
const sendMethod = require('../lib/hxtxChannel').send;
const crypto = require('crypto');
const utils = require("../lib/utils");
const { config } = require("bluebird");

const status = {
    MT: {
        Params_Miss: { code: 1002, msg: '必填参数字段缺失' },
        INVALID_sig: { code: 1001, msg: '签名验证失败' },
        INVALID_ext: { code: 1003, msg: 'extend 格式不正确，必须为 4 位以上纯数字串' },
        INVALID_appid: { code: 1004, msg: 'appid 不存在' },
        SYSTEM_ERR : {code : 5001, msg: '系统内部错误'}
    }
}
const appConfig = {
    'HXwz01': {
        appkey: 'c9aacd25eecf2e6cc051d60eed30c1fd', // appId 对应 appKey,
        sign : '【微众银行】',
        append: '拒收请回复R'
    },
    'HXwz02': {
        appkey: '79629822fae19f61781582b96e05472a', // appId 对应 appKey,
        sign : '【微众银行】',
        append: '拒收请回复R'
    },
    'HXwz03': {
        appkey: '988bf1309b5201dd8abb8a35ae525649', // appId 对应 appKey,
        sign : '【微众银行】',
        append: '拒收请回复R'
    },
    'HXwz04': {
        appkey: 'd19005b745cf9526d3fb344ad1e57acc', // appId 对应 appKey,
        sign : '【微众银行】',
        append: '拒收请回复R'
    },
    'HXwztt': {
        appkey: 'abb0b93f3f55ca3c', // appId 对应 appKey,
        sign : '【微众银行】',
        append: '拒收请回复R'
    }
};

let sender = new MyEmitter(10, sendMethod, async (result) => { log.info(result) });
sender.name = 'wz_sms_send_thread';
sender.startup();

router.get('/', async function (ctx, next) {
    ctx.state = {
        title: 'WZBANK'
    };

    await ctx.render('index', {
    });
})

async function commonValid(ctx) {

    const { appid, session, extend, sig, mobile, content, timestamp } = ctx.request.body;
    // 验证必填参数
    ctx.assert(appid && session && sig && mobile && content && timestamp, status.MT.Params_Miss);

    // 验证 sig
    let digStr = `appkey=${appConfig[appid].appkey}&random=${ctx.query.random}&time=${timestamp}&mobile=${mobile}`;
    
    const expectedSig = crypto.createHash('sha256').update(digStr).digest('hex');
    
    ctx.assert(sig == expectedSig, status.MT.INVALID_sig);
    // 验证 extend 格式
    ctx.assert(extend && /^\d*$/.test(extend), status.MT.INVALID_ext);

    let customer = await models.customer.findOne({ account: appid });
    ctx.assert(customer, status.MT.INVALID_appid)

    return customer;
}

async function doSubmit(ctx, batch) {
    // let admin = ctx.session.admin;
    let body = ctx.request.body;
    log.info('submit info: ', JSON.stringify(body), JSON.stringify(ctx.query), JSON.stringify(ctx.query));

    
    let reqLog = await models.mtRequestLog.create({ body });

    let customerInfo = await commonValid(ctx);
    const { appid, session, extend, sig, mobile, content, timestamp } = ctx.request.body;

    const sendContent = appConfig[appid].sign + content + appConfig[appid].append;
    let fee = utils.feeCount(sendContent);

    let mt_record = {
        request_id: reqLog._id,
        account: customerInfo.account,
        mobile,
        content : sendContent,
        charge_count: fee,
        ref: session,
        mt_msg_id: '',
        ext: extend,
    }

    try {
        record = await models.mtMsg.create(mt_record);
        record.password = customerInfo.password;
        record.ext = extend;
        sender.addTask(record);

        return {
            code: 0,
            errMsg: "OK",
            fee,
            messageId: reqLog._id,
        };
    } catch (err) {
        log.error('submit err', err);
        return {
            code: this.status.MT.SYSTEM_ERR.code,
            errMsg: this.status.MT.SYSTEM_ERR.msg,
            fee,
            messageId: reqLog._id,
        };
    }
}

router.get('/sms/send', httpResult.respSF(() => {
    throw ({ code: 405, message: 'METHOD NOT ALLOWED' });
}));

router.post('/sms/send', httpResult.respRaw(doSubmit));


module.exports = router;
